package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.TcScore;
import com.zhentao.service.TcScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("tea/score")
public class ScoreController {

    @Autowired
    TcScoreService scoreService;

    /**
     * 获取全部成绩
     */
    @GetMapping("list")
    public List<TcScore> list(){
        return scoreService.list();
    }

    /**
     * 根据ID获取成绩详情
     */
    @GetMapping("get/{id}")
    public TcScore getById(@PathVariable Integer id){
        return scoreService.getById(id);
    }

    /**
     * 添加成绩
     */
    @PostMapping("add")
    public Map<String, Object> add(@RequestBody TcScore score){
        Map<String, Object> result = new HashMap<>();
        try {
            score.setCreateTime(new Date());
            boolean success = scoreService.save(score);
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
            if (success) {
                result.put("data", score);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新成绩
     */
    @PutMapping("update")
    public Map<String, Object> update(@RequestBody TcScore score){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = scoreService.updateById(score);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            if (success) {
                result.put("data", score);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除成绩
     */
    @DeleteMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = scoreService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据班级ID获取成绩
     */
    @GetMapping("classScores/{classId}")
    public List<TcScore> getClassScores(@PathVariable String classId){
        QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.orderByDesc("create_time");
        return scoreService.list(queryWrapper);
    }

    /**
     * 根据学生ID获取成绩
     */
    @GetMapping("studentScores/{studentUserId}")
    public List<TcScore> getStudentScores(@PathVariable String studentUserId){
        QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_user_id", studentUserId);
        queryWrapper.orderByDesc("create_time");
        return scoreService.list(queryWrapper);
    }

    /**
     * 根据科目获取成绩
     */
    @GetMapping("subjectScores/{subject}")
    public List<TcScore> getSubjectScores(@PathVariable String subject){
        QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("subject", subject);
        queryWrapper.orderByDesc("create_time");
        return scoreService.list(queryWrapper);
    }

    /**
     * 根据考试名称获取成绩
     */
    @GetMapping("examScores/{examName}")
    public List<TcScore> getExamScores(@PathVariable String examName){
        QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_name", examName);
        queryWrapper.orderByDesc("score");
        return scoreService.list(queryWrapper);
    }

    /**
     * 获取班级某科目成绩排名
     */
    @GetMapping("classSubjectRanking/{classId}/{subject}")
    public List<TcScore> getClassSubjectRanking(@PathVariable String classId, @PathVariable String subject){
        QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.eq("subject", subject);
        queryWrapper.orderByDesc("score");
        return scoreService.list(queryWrapper);
    }

    /**
     * 获取学生某科目成绩历史
     */
    @GetMapping("studentSubjectHistory/{studentUserId}/{subject}")
    public List<TcScore> getStudentSubjectHistory(@PathVariable String studentUserId, @PathVariable String subject){
        QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_user_id", studentUserId);
        queryWrapper.eq("subject", subject);
        queryWrapper.orderByDesc("create_time");
        return scoreService.list(queryWrapper);
    }

    /**
     * 搜索成绩
     */
    @GetMapping("search")
    public List<TcScore> searchScores(@RequestParam String keyword){
        QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("exam_name", keyword).or().like("subject", keyword);
        queryWrapper.orderByDesc("create_time");
        return scoreService.list(queryWrapper);
    }

    /**
     * 批量添加成绩
     */
    @PostMapping("batchAdd")
    public Map<String, Object> batchAdd(@RequestBody List<TcScore> scores){
        Map<String, Object> result = new HashMap<>();
        try {
            Date now = new Date();
            for (TcScore score : scores) {
                score.setCreateTime(now);
            }
            boolean success = scoreService.saveBatch(scores);
            result.put("success", success);
            result.put("message", success ? "批量添加成功" : "批量添加失败");
            if (success) {
                result.put("data", scores);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量添加失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 批量删除成绩
     */
    @DeleteMapping("batchDelete")
    public Map<String, Object> batchDelete(@RequestBody List<Integer> ids){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = scoreService.removeByIds(ids);
            result.put("success", success);
            result.put("message", success ? "批量删除成功" : "批量删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取班级平均分
     */
    @GetMapping("classAverage/{classId}/{subject}")
    public Map<String, Object> getClassAverage(@PathVariable String classId, @PathVariable String subject){
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId);
            queryWrapper.eq("subject", subject);
            List<TcScore> scores = scoreService.list(queryWrapper);
            
            if (scores.isEmpty()) {
                result.put("average", 0);
                result.put("count", 0);
            } else {
                BigDecimal total = scores.stream()
                    .map(TcScore::getScore)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal average = total.divide(BigDecimal.valueOf(scores.size()), 2, BigDecimal.ROUND_HALF_UP);
                result.put("average", average);
                result.put("count", scores.size());
            }
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "计算平均分失败：" + e.getMessage());
        }
        return result;
    }
}
